"use strict";
var SGoObj=new Array();
var StoneCache=null;
var SGoPopup=new SGoUI_popup();

document.addEventListener("DOMContentLoaded", function(event) {
    StoneCache=new StoneGraphics();
    createDiagrams();    
});


if(!window.console)
{
    var console={
        log:function(){},
        debug:function(){},
        error:function(){},
        warn:function(){}
    };
}

function SGoUI_cancelBubble(e) 
{
    var evt = e ? e:window.event;
    if (evt.stopPropagation)    evt.stopPropagation();
    if (evt.cancelBubble!=null) evt.cancelBubble = true;
}

function SGoUI_handleEvent(event)
{

    var idstr, evname, evid, objindex, args, sgoobj;

    idstr=this.id;
    args=idstr.split("-");
    
    evname=args[0];
    objindex=parseInt(args[1]);
    evid=parseInt(args[2]);
    
    SGoUI_cancelBubble(event);

    sgoobj=SGoObj[objindex];
    if(sgoobj==undefined)
    {
        console.error("Invalid object selected: ", objindex);
        return;
    }
    if(evname=='SGoDrawArea')
        sgoobj.handleGobanEvent(this,event);
    else
        sgoobj.handleEvent(evname,evid);    
    
}

function createDiagrams()
{
    var i,j, sgodia, sgopre, obj, rawSGF;
    sgodia=document.getElementsByClassName("SGoDia");
    if(sgodia==null)
        return;
    for(i=0;i<sgodia.length;i++)
    {
        sgopre=sgodia[i].getElementsByTagName('pre');
        if(sgopre!=null)
        {
            for(j=0;j<sgopre.length;j++)
            {
		        obj=new SGoMain(SGoObj.length);
		        SGoObj.push(obj);
		        rawSGF=sgopre[j].innerHTML.replace(/<br>|<\/br>|<br \/>/g,"\n");
		        obj.renderDiagram(sgodia[i],rawSGF);
            }
        }
    }    
}



function SGoMain(diaindex)
{    
    this.m_box=null;
    this.m_goban=null;
    this.m_core=null;
    this.m_autoplay=null;
    this.m_rawsgf=null;
    
    this.m_config={
        index:0, default_stonesize:24, stonesize:24, autocrop:false,
        bounds:{left:0,top:0,right:19,bottom:19},
        margins:{left:true,top:true,right:true,bottom:true},
        commentpos:'bottom',filetype:'game',boxsize:{w:480,h:480},
        boardsize:{w:19,h:19},showvar:true,timeout:2000,coordinates:false,editmode:false
        };

    this.m_config.index=diaindex;

    this.renderDiagram=function(elem,rawsgf)
    {
        if(elem==null)
        {
            console.warn("Invalid sgo dia element");
            return;
        }
        this.m_rawsgf=rawsgf.substring(0,rawsgf.length);
        this.loadSGF(rawsgf);
        this.UIinit(elem);

    }
        
    this.gobanImageReady=function()
    {
        this.UIupdate();
    }

    this.UIinit=function(parent)
    {

        this.m_box=new SGoBox();
        this.m_box.init(parent,this.m_config);
        this.m_goban=new SGoGoban(this.m_box.m_drawarea);

        this.UIresize();
    }

    this.loadSGF=function(rawSGF)
    {
        var b, ssize, min_width, new_ssize, max_size;
        
        if(this.m_core==null)
        {
            this.m_core=new SGoCore();
        }
        this.parseConfig(rawSGF);
        this.m_core.loadSGF(rawSGF);

        /*add properties like AW,AB */
        this.m_core.addRootProps();
    }
    
    this.parseConfig = function(rawSGF)
    {
        var cfgstr,jsn;
        cfgstr=rawSGF.match(/\{.*?\}/);
        jsn=null;
        if(cfgstr!=null)
        {            
            jsn=JSON.parse( cfgstr[0] );
            
        }
        if(jsn == null)
            return;

        if(jsn.stonesize!=undefined)
        {
            this.m_config.stonesize=parseInt(jsn.stonesize);  
            this.m_config.default_stonesize=this.m_config.stonesize;
        }
        if(jsn.commentpos!=undefined)
        {
            this.m_config.commentpos=jsn.commentpos;
        }
        if(jsn.filetype!=undefined)
        {
            this.m_config.filetype=jsn.filetype;                            
        }
        if(jsn.autocrop!=undefined)
        {
             this.m_config.autocrop=jsn.autocrop
        }
        if(this.m_config.filetype=='problem')
        {
            this.m_config.showvar=false;
        }        
    }
    
    this.autoPlay=function()
    {
        var _this=this;
        
        if(_this.m_autoplay==null)
        {
            _this.m_box.changeLabel(SGoButton.BUT_ID_AUTOPLAY,"pause");
            _this.m_autoplay=setInterval(function(){
                var rv;
                rv=_this.moveNext(1);
                if(rv==false)
                {
                    clearInterval(_this.m_autoplay);
                    _this.m_autoplay=null;
                    _this.m_box.changeLabel(SGoButton.BUT_ID_AUTOPLAY,"play");
                }
            },_this.m_config.timeout);
        }
        else
        {
            clearInterval(_this.m_autoplay);
            _this.m_autoplay=null;
            _this.m_box.changeLabel(SGoButton.BUT_ID_AUTOPLAY,"play");
        }
    }
    
    this.computeStoneSize=function()
    {
        var max_width,b,ssize,max_boxwidth;
        
        ssize=this.m_config.default_stonesize;
        max_width = this.m_config.default_stonesize*20;
        max_boxwidth = this.m_box.getParentWidth();
                
        if(max_boxwidth < max_width)
        {
            max_width = max_boxwidth;
        }
               
        if(this.m_config.autocrop==true)
        {
            b=this.m_core.getBounds();
        }
        else
        {
            b=this.m_core.getDefaultBounds();
        }
        
        ssize=Math.round(max_width/(b.right-b.left+1));
        
        return ssize;
    }
    
    this.UIresize=function()
    {
        var ssize,b;

        this.m_box.setCommentPos(this.m_config.commentpos);
        this.m_box.changeNavLinks(this.m_config.filetype);
        b=this.m_core.getBounds();
        
        this.m_config.stonesize = this.computeStoneSize();
        
        if(this.m_config.autocrop==true)
        {
            this.m_config.bounds=this.m_core.getBounds();
        }
        else
        {
            this.m_config.bounds=this.m_core.getDefaultBounds();
        }
        
        b=this.m_config.bounds;
        this.m_config.margins=this.m_core.getMargins(b);
        this.m_config.boardsize.w=b.right-b.left;
        this.m_config.boardsize.h=b.bottom-b.top;
        
        ssize=this.m_config.stonesize;
        this.m_config.boxsize.w=Math.abs((b.right-b.left+1)*ssize);
        this.m_config.boxsize.h=Math.abs((b.bottom-b.top+1)*ssize);

        
        this.m_box.resize(this.m_config.boxsize.w, this.m_config.boxsize.h, ssize);
        this.m_goban.resize(this.m_config.boardsize.w, this.m_config.boardsize.h, ssize);
        this.m_goban.drawGrid(this.m_config.margins);

        if(this.m_core!=null)
        {
            this.m_box.setGameInfo(this.m_core.getGameInfo(this.m_config.filetype));
            this.UIupdate();
        }
        StoneCache.createStone('white',this.m_config.stonesize,this);
        StoneCache.createStone('black',this.m_config.stonesize,this);
    }
    
    this.drawMarkup=function()
    {
         var node,p,color,stone,b,i;
         
         b=this.m_config.bounds;
         node=this.m_core.getCurrentNode();
         
         if((node!=null) &&(node.m_prop!=null))
         {
             for(i=0;i<node.m_prop.length;i++)
             {
                p=node.m_prop[i];               
                if((p.m_x==-1) || (p.m_y==-1))
                    continue;
                    
                stone=this.m_core.getStone(p.m_x,p.m_y);                                
                color="#000000";
                if(stone!=null) 
                {
                    if(stone.m_color==SGFProp.COLOR_BLACK)
                        color="#FFFFFF";
                }
                else
                {
                    this.m_goban.clearRect(p.m_x-b.left, p.m_y-b.top);
                }                        
                
                if(p.m_id==SGFProp.ID_TR)
                {
                    this.m_goban.drawTriangle(color, p.m_x-b.left, p.m_y-b.top);                    
                }
                else if(p.m_id==SGFProp.ID_LB)
                {
                    this.m_goban.drawText(color, p.m_text, p.m_x-b.left, p.m_y-b.top);                    
                }
             }
         }
    }
    
    this.UIupdate=function()
    {
        var i,j,b,stone,varpos,x,y,lastind,varnr,color,node,show_var;        
        if(this.m_core==null)
            return
        
        this.m_goban.drawGrid(this.m_config.margins);
        b=this.m_config.bounds;
        if(this.m_config.coordinates==true)
            this.m_goban.drawCoordinates(b,this.m_config.margins);
            
        for(j=b.top;j<b.bottom;j++)
        {
            for(i=b.left;i<b.right;i++)
            {
                if(this.m_core.isHandi(i,j))
                {
                    this.m_goban.drawHandi(i-b.left,j-b.top);
                }
                stone=this.m_core.getStone(i,j);
                if(stone==null)
                    continue;
                if((stone.m_color==SGFProp.COLOR_BLACK)||
                   (stone.m_color==SGFProp.COLOR_WHITE))
                {
                    x=i-b.left;
                    y=j-b.top;
                    this.m_goban.drawStone(stone.m_color,x,y);
                    color="#000000";
                    if((this.m_config.filetype=="problem") && (stone.m_index!=0))
                    {
                        if(stone.m_color==SGFProp.COLOR_BLACK)
                            color="#FFFFFF";
                        this.m_goban.drawText(color,""+stone.m_index,x,y);
                    }
                }
            }

         }
         
         this.drawMarkup();
         
         /* draw last index */
         if(this.m_config.filetype=="game")
         {
            node=this.m_core.getCurrentNode();
            stone=node.m_stone;
            if(stone!=null)
            {
                color="#000000";
                if(stone.m_color==SGFProp.COLOR_BLACK)
                    color="#FFFFFF";
                this.m_goban.drawText(color,""+stone.m_index,
                    stone.m_x-b.left,stone.m_y-b.top);
            }
         }

         this.m_box.addComment(this.m_core.getCurrentComment());

         /*add variation */
         this.m_box.hideVariations();
         varpos=this.m_core.getChidrenPos();
         node=this.m_core.getCurrentNode();
         show_var=this.m_config.showvar;
         if((this.m_config.filetype=="game") && (node.getNumberOfChilds() ==0))
         {
            show_var=false;
         }
         if(varpos!=null)
         {
            for(i=0;i<varpos.length;i++)
            {
                if((varpos[i].x==-1) || (varpos[i].y==-1))
                    break;
                this.m_box.showVariations(i, varpos[i].x-b.left, varpos[i].y-b.top,show_var);
            }
         }
    }
    
    this.setEditable=function()
    {
        this.m_box.setEditable(this.m_config.editmode);
    }
    
    this.moveNext=function(steps)
    {
        var i,status;
        
        status=false;
        if(steps==-1) 
            steps=381;
            
        for(i=0;i<steps;i++)
        {
            status=this.m_core.moveNext(1);
            if(status==false)
                break;
        }
        this.UIupdate();
        return status;
    }

    this.movePrev=function(steps)
    {
        var i,status;
                
        status=false;                
        if(steps==-1) 
            steps=381;            
            
        for(i=0;i<steps;i++)
        {
            status=this.m_core.movePrev(1);
            if(status==false)
                break;
        }
        this.UIupdate();
    }

    this.moveChild=function(cid)
    {
        this.m_core.moveChild(cid);
        this.UIupdate();
    }

    this.restart=function()
    {
        this.m_core.restart();
        this.UIupdate();
    }

    this.showAnswer=function()
    {
        var i,steps=381,status;
        this.m_core.restart();

        for(i=0;i<steps;i++)
        {
            status=this.m_core.moveNext(1);
            if(status==false)
                break;
        }
        this.m_config.showvar=true;
        this.UIupdate();
        
    }
    
    this.handleGobanEvent=function(elem, event)
    {
        var pos,bpos;
        pos=SGo_getClickPos(elem,event);
        bpos=this.m_goban.getPointAt(pos.x,pos.y);
        bpos.x += this.m_config.bounds.left;
        bpos.y += this.m_config.bounds.top;
        this.m_core.addMove(bpos.x,bpos.y);
        this.UIupdate();
        
    }
    
    this.handleEvent=function(evname,evid)
    {
        var rv,_this,lbl;
        
        switch(evname)
        {
            case SGoButton.BUT_ID_VARIATION:
                 if(evid==0)
                 {
                    rv=this.moveNext(1);
                 }
                 else
                 {
                    rv=this.moveChild(evid-1);
                    /*rv=this.moveNext(1);*/
                 }
                 _this=this;
                 setTimeout(function(){rv=_this.moveNext(1);},500);
                 break;
		    case SGoButton.BUT_ID_START:
                rv=this.movePrev(-1);
	    		break;

		    case SGoButton.BUT_ID_END:	
		        if(this.m_config.filetype=='problem')	        
		        {
		            this.showAnswer();
		        }
		        else
		        {
	                rv=this.moveNext(-1);
	            }
				break;

		    case SGoButton.BUT_ID_PREV:
				rv=this.movePrev(1);
				break;

            case SGoButton.BUT_ID_NEXT:
                rv=this.moveNext(1);
                break;
            case SGoButton.BUT_ID_AUTOPLAY:
                rv=this.autoPlay();
                break;            
                
            case SGoButton.BUT_ID_CONFIG:     
                 //SGoPopup.show(this.m_rawsgf);                             
                 SGoPopup.show(this);
                 break;
		}
    }
}


